// File: jmcomic-core/src/main/java/dev/jukomu/common/postman/impl/CurlCffiPostman.java
package dev.jukomu.common.postman.impl;

import dev.jukomu.common.postman.AbstractPostman;
import dev.jukomu.common.postman.Postman;
import okhttp3.OkHttpClient;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 对应Python的CurlCffiPostman，在Java中，我们将使用OkHttp作为底层实现。
 * 'impersonate'参数将被忽略，因为OkHttp不直接支持浏览器指纹模拟。
 */
public class CurlCffiPostman extends AbstractPostman {

    public static String POSTMAN_KEY = "curl_cffi"; // 对应Python的postman_key

    private final OkHttpClient defaultClient; // 用于执行请求的OkHttpClient实例

    /**
     * 构造函数。
     *
     * @param kwargs 初始化参数Map。
     */
    public CurlCffiPostman(Map<String, Object> kwargs) {
        super(kwargs);
        this.defaultClient = buildClient(kwargs);
    }

    // 辅助方法：构建OkHttpClient实例 (与OkHttpPostman相同逻辑，但会打印impersonate警告)
    protected OkHttpClient buildClient(Map<String, Object> kwargs) {
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();

        // 处理timeout
        Number timeout = (Number) kwargs.get("timeout");
        if (timeout != null) {
            clientBuilder.connectTimeout(timeout.longValue(), TimeUnit.SECONDS)
                    .readTimeout(timeout.longValue(), TimeUnit.SECONDS)
                    .writeTimeout(timeout.longValue(), TimeUnit.SECONDS);
        }

        // 处理allow_redirects
        Boolean allowRedirects = (Boolean) kwargs.get("allow_redirects");
        if (allowRedirects != null) {
            clientBuilder.followRedirects(allowRedirects);
            clientBuilder.followSslRedirects(allowRedirects);
        }

        // 处理proxies
        Map<String, String> proxies = (Map<String, String>) kwargs.get("proxies");
        if (proxies != null && !proxies.isEmpty()) {
            String socksAddress = proxies.get("socks");
            if (socksAddress != null && socksAddress.startsWith("socks://")) {
                String[] parts = socksAddress.substring("socks://".length()).split(":");
                if (parts.length == 2) {
                    clientBuilder.proxy(new java.net.Proxy(java.net.Proxy.Type.SOCKS, new java.net.InetSocketAddress(parts[0], Integer.parseInt(parts[1]))));
                }
            } else {
                String httpAddress = proxies.get("http");
                if (httpAddress != null && (httpAddress.startsWith("http://") || httpAddress.startsWith("https://"))) {
                    String cleanAddress = httpAddress.replaceFirst("^(http|https)://", "");
                    String[] parts = cleanAddress.split(":");
                    if (parts.length == 2) {
                        clientBuilder.proxy(new java.net.Proxy(java.net.Proxy.Type.HTTP, new java.net.InetSocketAddress(parts[0], Integer.parseInt(parts[1]))));
                    }
                }
            }
        }

        // 处理verify (SSL验证)
        Boolean verify = (Boolean) kwargs.get("verify");
        if (verify != null && !verify) {
            clientBuilder.hostnameVerifier((hostname, session) -> true);
            try {
                javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[]{
                        new javax.net.ssl.X509TrustManager() {
                            @Override
                            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                            }

                            @Override
                            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                            }

                            @Override
                            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                                return new java.security.cert.X509Certificate[]{};
                            }
                        }
                };
                javax.net.ssl.SSLContext sslContext = javax.net.ssl.SSLContext.getInstance("SSL");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                clientBuilder.sslSocketFactory(sslContext.getSocketFactory(), (javax.net.ssl.X509TrustManager) trustAllCerts[0]);
            } catch (Exception e) {
                System.err.println("Failed to disable SSL verification: " + e.getMessage());
            }
        }

        // 处理impersonate：对于OkHttp，impersonate参数会被忽略
        if (kwargs.containsKey("impersonate")) {
            System.err.println("Warning: 'impersonate' parameter is ignored by CurlCffiPostman as it's specific to curl_cffi. This is a placeholder for a no-impersonation HTTP client.");
        }

        return clientBuilder.build();
    }

    @Override
    protected Postman getRequestExecutor() {
        // 复用OkHttpPostman内部的执行器
        return new OkHttpPostman.OkHttpExecutor(defaultClient, metaData);
    }

    @Override
    protected Postman postRequestExecutor() {
        return new OkHttpPostman.OkHttpExecutor(defaultClient, metaData);
    }

    @Override
    public Postman copy() {
        return new CurlCffiPostman(new HashMap<>(metaData));
    }
}